package com.bidevalution.business.job;
import com.bidevalution.business.factory.StepJobJdbcFactory;
import com.bidevalution.business.service.JdbcTemplateService;
import com.bidevalution.dao.entity.BeEvalutionExpert;
import com.bidevalution.dao.entity.BeSectionExpertInfo;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.dao.entity.BeSectionStep;
import com.bidevalution.dao.entity.BeSectionStepJob;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.IdsUtil;
import com.qtp.core.util.OConvertUtils;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 商务标评审-计算错误检查计算
 * @author: xiayf
 * @date: 2019-10-14 15:07
 */
public class ComputerErrorCheckJob implements StepJobJdbcFactory {

    private static Logger log = Logger.getLogger(ComputerErrorCheckJob.class);

    private JdbcTemplateService jdbcTemplateService;

   

    @Override
    public Boolean execute(BeSectionStepJob beSectionStepJob, String submitCode,String expertId,String layouCode) throws Exception {
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("sectionStepId", beSectionStepJob.getSectionStepId());
            paramMap.put("submitCode", submitCode);
            paramMap.put("sectionId", beSectionStepJob.getSectionId());
            RowMapper<BeSectionInfo> rm = BeanPropertyRowMapper.newInstance(BeSectionInfo.class);
            BeSectionInfo beSectionInfo = jdbcTemplateService.selectForObject(" select td_projectId from be_section_info where seq_id=:sectionId ",paramMap,rm);
            paramMap.put("tdProjectId", beSectionInfo.getTdProjectid());
            String sqlStr = " select v.BidID enterpriseId,sum(errorCount) errorCount  from (    " +
                            "   select bn.enterprise_id as BidID,bn.mano_ManageNodeID as ManageNodeID,    " +
                            "   case when ABS(Round(v1.TotalCost, 2)-ifnull(bn.mano_Total,0)>=ifnull(bn.mano_Total,0)*0.005) then 1 else 0 end as errorCount   " +
                            "   from td_ManageNode_Bid bn   " +
                            "   join (select mano_ProjectID,enterprise_id, mano_ManageNodeID,mano_IdxCode,sum(Total) as TotalCost    " +
                            "   from (select mano_ProjectID, enterprise_id, mano_ManageNodeID, mano_Name, mano_IdxCode, 1 as CostType,    " +
                            "   (select sum(buno_Total) from td_BudgetNode_Bid    " +
                            "   where buno_ManageNodeID=mn.mano_ManageNodeID and buno_ProjectID = mn.mano_ProjectID and enterprise_id = mn.enterprise_id and buno_Type = 2   " +
                            "   ) as Total    " +
                            "   from td_ManageNode_Bid mn    " +
                            "   where mn.mano_ProjectID=:tdProjectId   " +
                            "   union    " +
                            "   select mano_ProjectID, enterprise_id, mano_ManageNodeID, mano_Name, mano_IdxCode,2.1 as CostType,    " +
                            "   (select sum(meno_Total) from td_MeasuresNode_Bid    " +
                            "   where meno_ManageNodeID=mn.mano_ManageNodeID and meno_ProjectID = mn.mano_ProjectID and enterprise_id = mn.enterprise_id and length(meno_IdxCode)=9 and left(meno_Type, 1)='1'   " +
                            "   ) as Total   " +
                            "   from td_ManageNode_Bid mn   " +
                            "   where mn.mano_ProjectID=:tdProjectId   " +
                            "   union    " +
                            "   select mano_ProjectID, enterprise_id, mano_ManageNodeID, mano_Name, mano_IdxCode,2 as CostType,    " +
                            "   (select sum(meno_Total) from td_MeasuresNode_Bid    " +
                            "   where meno_ManageNodeID=mn.mano_ManageNodeID and meno_ProjectID = mn.mano_ProjectID and enterprise_id = mn.enterprise_id and length(meno_IdxCode)>6 and meno_Type = '2'   " +
                            "   ) as Total   " +
                            "   from td_ManageNode_Bid mn   " +
                            "   where mn.mano_ProjectID=:tdProjectId   " +
                            "   union    " +
                            "   select mano_ProjectID, enterprise_id, mano_ManageNodeID, mano_Name, mano_IdxCode,3 as CostType,    " +
                            "   (select sum(otno_Total) from td_OtherNode_Bid    " +
                            "   where otno_ManageNodeID=mn.mano_ManageNodeID and otno_ProjectID = mn.mano_ProjectID and enterprise_id = mn.enterprise_id and length(otno_IdxCode)=6   " +
                            "   ) as Total    " +
                            "   from td_ManageNode_Bid mn    " +
                            "   where mn.mano_ProjectID=:tdProjectId   " +
                            "   union    " +
                            "   select mano_ProjectID, enterprise_id, mano_ManageNodeID, mano_Name, mano_IdxCode,4 as CostType,    " +
                            "   (select sum(otco_Total) from td_OtherCost_Bid    " +
                            "   where otco_ManageNodeID=mn.mano_ManageNodeID and otco_CostType = '41' and otco_ProjectID = mn.mano_ProjectID and enterprise_id = mn.enterprise_id   " +
                            "   ) as Total    " +
                            "   from td_ManageNode_Bid mn    " +
                            "   where mn.mano_ProjectID=:tdProjectId   " +
                            "   union    " +
                            "   select mano_ProjectID, enterprise_id, mano_ManageNodeID, mano_Name, mano_IdxCode,4 as CostType,    " +
                            "   (select sum(otco_Total) from td_OtherCost_Bid    " +
                            "   where otco_ManageNodeID=mn.mano_ManageNodeID and otco_CostType = '42' and otco_ProjectID = mn.mano_ProjectID and enterprise_id = mn.enterprise_id   " +
                            "   ) as Total    " +
                            "   from td_ManageNode_Bid mn    " +
                            "   where mn.mano_ProjectID=:tdProjectId   " +
                            "   union    " +
                            "   select mano_ProjectID, enterprise_id, mano_ManageNodeID, mano_Name, mano_IdxCode,5 as CostType,    " +
                            "   (select sum(otco_Total) from td_OtherCost_Bid    " +
                            "   where otco_ManageNodeID=mn.mano_ManageNodeID and otco_CostType = '5' and otco_ProjectID = mn.mano_ProjectID and enterprise_id = mn.enterprise_id   " +
                            "   ) as Total    " +
                            "   from td_ManageNode_Bid mn    " +
                            "   where mn.mano_ProjectID=:tdProjectId   " +
                            "   union    " +
                            "   select mano_ProjectID, enterprise_id, mano_ManageNodeID, mano_Name, mano_IdxCode,0 as CostType,    " +
                            "   (select sum(mano_Total) from td_ManageNode_Bid    " +
                            "   where mano_ParentID=mn.mano_ManageNodeID and mano_ProjectID = mn.mano_ProjectID and enterprise_id = mn.enterprise_id   " +
                            "   ) as Total    " +
                            "   from td_ManageNode_Bid mn    " +
                            "   where mn.mano_ProjectID=:tdProjectId   " +
                            "   ) as v   " +
                            "   group by mano_ProjectID,enterprise_id, mano_ManageNodeID,mano_IdxCode    " +
                            "   ) as v1  on bn.mano_ProjectID = v1.mano_ProjectID and bn.enterprise_id = v1.enterprise_id and bn.mano_ManageNodeID = v1.mano_ManageNodeID   " +
                            "   where exists(select * from td_ManageNode_Bid where mano_ProjectID = bn.mano_ProjectID and enterprise_id = bn.enterprise_id and mano_ParentID = bn.mano_ManageNodeID)) v   " +
                            "   group by BidID";
            List<Map<String, Object>> enterList = jdbcTemplateService.selectForList(sqlStr, paramMap);
            //保存计算结果
            saveResult(paramMap, enterList);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Exception("*****计算商务标评审-计算错误检查失败*****");
        }
    }

    private void saveResult(Map<String, Object> paramMap, List<Map<String, Object>> enterList) throws Exception {
        try {
            RowMapper<BeSectionExpertInfo> rm1 = BeanPropertyRowMapper.newInstance(BeSectionExpertInfo.class);
            List<BeSectionExpertInfo> beSectionExpertInfoList = jdbcTemplateService.selectForList(" select " +
                    "    seq_id, section_id, name, login_name, card_no, work_unit, phone, expert_type, area_type, " +
                    "    is_avoid, avoid_reason, is_manager, update_time, create_time " +
                    "    from be_section_expert_info " +
                    "    where section_id=:sectionId", paramMap, rm1);
            RowMapper<BeSectionStep> rm2 = BeanPropertyRowMapper.newInstance(BeSectionStep.class);
            BeSectionStep beSectionStep = jdbcTemplateService.selectForObject(" select " +
                    "    seq_id, section_id, step_code, step_name, parent_code, order_num, step_url, related_step_code,  " +
                    "    related_layout_code, related_column_code, related_step_id, create_time, update_time,load_function" +
                    "    from be_section_step " +
                    "     where section_id=:sectionId and step_code = '64'", paramMap, rm2);
            paramMap.put("sectionStepId", beSectionStep.getSeqId());
            paramMap.put("relatedColumnCode", beSectionStep.getRelatedColumnCode());
            //删除已存在结果
            jdbcTemplateService.update(" DELETE FROM be_evalution_expert WHERE section_id=:sectionId AND section_step_id=:sectionStepId " +
                    " AND submit_code=:submitCode AND column_code=:relatedColumnCode ", paramMap);
            jdbcTemplateService.update(" DELETE FROM be_evalution_expert WHERE section_id=:sectionId AND section_step_code='64' " +
                    "AND submit_code=:submitCode ", paramMap);
            List<BeEvalutionExpert> beEvalutionExpertList = new ArrayList<>();
            BeEvalutionExpert beEvalutionExpert = null;
            for (BeSectionExpertInfo beSectionExpertInfo : beSectionExpertInfoList) {
                for (Map<String, Object> map : enterList) {
                    beEvalutionExpert = new BeEvalutionExpert();
                    beEvalutionExpert.setSeqId(IdsUtil.uuid());
                    beEvalutionExpert.setExpertId(beSectionExpertInfo.getSeqId());
                    beEvalutionExpert.setSectionId(OConvertUtils.getString(paramMap.get("sectionId")));
                    beEvalutionExpert.setColumnCode("errorCount");
                    beEvalutionExpert.setColumnValue(OConvertUtils.getString(map.get("errorCount")));
                    beEvalutionExpert.setEnterpriseId(OConvertUtils.getString(map.get("enterpriseId")));
                    beEvalutionExpert.setSectionStepId(beSectionStep.getSeqId());
                    beEvalutionExpert.setSectionStepCode(beSectionStep.getStepCode());
                    beEvalutionExpert.setLayoutCode("Top");
                    beEvalutionExpert.setSubmitCode(OConvertUtils.getString(paramMap.get("submitCode")));
                    beEvalutionExpert.setCreateTime(DateUtil.now());
                    beEvalutionExpert.setUpdateTime(DateUtil.now());
                    beEvalutionExpertList.add(beEvalutionExpert);

                    beEvalutionExpert = new BeEvalutionExpert();
                    beEvalutionExpert.setSeqId(IdsUtil.uuid());
                    beEvalutionExpert.setExpertId(beSectionExpertInfo.getSeqId());
                    beEvalutionExpert.setColumnCode(beSectionStep.getRelatedColumnCode());
                    if (OConvertUtils.getInt(map.get("errorCount")) > 0) {
                        beEvalutionExpert.setColumnValue("0");
                    } else {
                        beEvalutionExpert.setColumnValue("1");
                    }
                    beEvalutionExpert.setEnterpriseId(OConvertUtils.getString(map.get("enterpriseId")));
                    beEvalutionExpert.setSectionId(OConvertUtils.getString(paramMap.get("sectionId")));
                    beEvalutionExpert.setSectionStepId(beSectionStep.getRelatedStepId());
                    beEvalutionExpert.setSectionStepCode(beSectionStep.getRelatedStepCode());
                    beEvalutionExpert.setLayoutCode(beSectionStep.getRelatedLayoutCode());
                    beEvalutionExpert.setSubmitCode(OConvertUtils.getString(paramMap.get("submitCode")));
                    beEvalutionExpert.setCreateTime(DateUtil.now());
                    beEvalutionExpert.setUpdateTime(DateUtil.now());
                    beEvalutionExpertList.add(beEvalutionExpert);
                }
            }
            //批量转数组
            SqlParameterSource[] beanSources = SqlParameterSourceUtils.createBatch(beEvalutionExpertList);
            jdbcTemplateService.bathInsert(" insert into be_evalution_expert (seq_id, section_step_id, section_id, " +
                    "    column_code, expert_id, column_value,submit_code,row_key,layout_code,enterprise_id,section_step_code,create_time, " +
                    "    update_time) " +
                    "    values(:seqId, :sectionStepId, :sectionId,:columnCode, :expertId, :columnValue,:submitCode,:rowKey," +
                    "   :layoutCode,:enterpriseId,:sectionStepCode,:createTime,:updateTime)", beanSources);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Exception("*****保存商务标评审-计算错误检查结果失败*****");
        }
    }

	@Override
	public void setJdbcTemplateService(JdbcTemplateService jdbcTemplateService) {
		this.jdbcTemplateService = jdbcTemplateService;
	}


}
